{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Pandas 删除数据 - drop() 方法详解\n\n本教程详细介绍如何使用 `drop()` 方法删除 DataFrame 中的行和列。\n\n## 目录\n1. 删除列\n2. 删除行\n3. drop() 参数详解\n4. 其他删除方法\n5. 删除重复数据\n6. 删除缺失值"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 导入库"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\nimport numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. 删除列\n\n### 方法说明\n\n使用 `drop()` 方法删除列。\n\n**语法:**\n```python\ndf.drop(columns=['列名1', '列名2', ...])\n# 或\ndf.drop(['列名1', '列名2'], axis=1)\n```\n\n**参数:**\n- `columns`: 要删除的列名列表\n- `axis=1`: 表示删除列（axis=0 表示删除行）\n- `inplace`: 是否直接修改原 DataFrame（默认 False）\n\n**特点:**\n- ✅ 默认返回新 DataFrame\n- ✅ 可以同时删除多列\n- ✅ 支持 errors 参数处理不存在的列\n\n**适用场景:** 需要删除一列或多列时"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例1: 创建示例数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.DataFrame({\n    '姓名': ['张三', '李四', '王五'],\n    '年龄': [25, 30, 35],\n    '城市': ['北京', '上海', '广州'],\n    '工资': [8000, 12000, 15000]\n})\n\nprint(\"原始 DataFrame:\")\nprint(df)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例2: 删除单列\n\n删除工资列，原 DataFrame 不变。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_new = df.drop('工资', axis=1)\nprint(\"删除单列:\")\nprint(df_new)\nprint(\"\\n原 DataFrame 未改变:\")\nprint(df)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例3: 删除多列\n\n同时删除年龄和工资两列。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_new = df.drop(['年龄', '工资'], axis=1)\nprint(\"删除多列:\")\nprint(df_new)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例4: 使用 columns 参数\n\n更明确的语法，推荐使用。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_new = df.drop(columns=['城市', '工资'])\nprint(\"使用 columns 参数:\")\nprint(df_new)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例5: inplace 参数\n\n⚠️ 使用 `inplace=True` 会直接修改原 DataFrame，一般不推荐。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_copy = df.copy()\ndf_copy.drop('工资', axis=1, inplace=True)\nprint(\"使用 inplace=True:\")\nprint(df_copy)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. 删除行\n\n### 方法说明\n\n使用 `drop()` 方法删除行。\n\n**语法:**\n```python\ndf.drop(index=['索引1', '索引2', ...])\n# 或\ndf.drop(['索引1', '索引2'], axis=0)\n```\n\n**参数:**\n- `index`: 要删除的索引列表\n- `axis=0`: 表示删除行（默认值）\n\n**特点:**\n- 根据索引标签删除，不是位置\n- 可以删除单行或多行\n\n**适用场景:** 需要删除特定行时"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例1: 创建带索引的示例数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.DataFrame({\n    '姓名': ['张三', '李四', '王五', '赵六'],\n    '年龄': [25, 30, 35, 40],\n    '城市': ['北京', '上海', '广州', '深圳']\n}, index=['A', 'B', 'C', 'D'])\n\nprint(\"原始 DataFrame:\")\nprint(df)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例2: 删除单行\n\n删除索引为 'B' 的行。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_new = df.drop('B')\nprint(\"删除单行:\")\nprint(df_new)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例3: 删除多行\n\n删除索引为 'A' 和 'C' 的行。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_new = df.drop(['A', 'C'])\nprint(\"删除多行:\")\nprint(df_new)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例4: 使用 index 参数\n\n更明确的语法。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_new = df.drop(index=['B', 'D'])\nprint(\"使用 index 参数:\")\nprint(df_new)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例5: 删除数字索引的行\n\n对于默认的数字索引，直接使用数字。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_numeric = pd.DataFrame({\n    '姓名': ['张三', '李四', '王五', '赵六'],\n    '年龄': [25, 30, 35, 40]\n})\n\nprint(\"原始 DataFrame（数字索引）:\")\nprint(df_numeric)\n\ndf_new = df_numeric.drop([0, 2])\nprint(\"\\n删除索引 0 和 2:\")\nprint(df_new)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. drop() 参数详解\n\n详细说明 `drop()` 方法的各个参数。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 参数1: axis\n\n**说明:**\n- `axis=0` 或 `axis='index'`: 删除行\n- `axis=1` 或 `axis='columns'`: 删除列"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.DataFrame({\n    'A': [1, 2, 3],\n    'B': [4, 5, 6],\n    'C': [7, 8, 9]\n})\n\nprint(\"原始 DataFrame:\")\nprint(df)\n\nprint(\"\\naxis=0 (删除行):\")\nprint(df.drop(0, axis=0))\n\nprint(\"\\naxis=1 (删除列):\")\nprint(df.drop('A', axis=1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 参数2: errors\n\n**说明:**\n- `errors='raise'` (默认): 如果标签不存在，抛出 KeyError\n- `errors='ignore'`: 忽略不存在的标签\n\n**适用场景:** 不确定列是否存在时使用 `errors='ignore'`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n    df.drop('X', axis=1)  # 列 X 不存在\nexcept KeyError as e:\n    print(f\"错误: {e}\")\n\nprint(\"\\n使用 errors='ignore':\")\ndf_new = df.drop('X', axis=1, errors='ignore')\nprint(df_new)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 参数3: inplace\n\n**说明:**\n- `inplace=False` (默认): 返回新 DataFrame\n- `inplace=True`: 直接修改原 DataFrame，返回 None\n\n**注意:** 一般不推荐使用 `inplace=True`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_copy = df.copy()\nresult = df_copy.drop('A', axis=1, inplace=True)\nprint(\"inplace=True 返回值:\")\nprint(result)  # None\nprint(\"\\n原 DataFrame 被修改:\")\nprint(df_copy)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. 其他删除方法\n\n除了 `drop()`，还有其他删除列的方法。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 方法1: 使用 del 关键字\n\n**特点:**\n- 直接修改原 DataFrame\n- 只能删除单列\n- 不返回任何值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.DataFrame({\n    '姓名': ['张三', '李四', '王五'],\n    '年龄': [25, 30, 35],\n    '城市': ['北京', '上海', '广州']\n})\n\ndf_copy = df.copy()\ndel df_copy['城市']\nprint(\"使用 del:\")\nprint(df_copy)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 方法2: 使用 pop() 方法\n\n**特点:**\n- 删除列并返回该列\n- 直接修改原 DataFrame\n\n**适用场景:** 需要删除列并使用该列数据时"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_copy = df.copy()\nremoved_col = df_copy.pop('年龄')\nprint(\"使用 pop():\")\nprint(\"被删除的列:\")\nprint(removed_col)\nprint(\"\\n剩余 DataFrame:\")\nprint(df_copy)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 方法3: 使用布尔索引删除行\n\n**特点:**\n- 更灵活的条件删除\n- 基于条件而非索引\n\n**适用场景:** 根据条件删除行"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_new = df[df['年龄'] != 30]  # 删除年龄为30的行\nprint(\"使用布尔索引:\")\nprint(df_new)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. 删除重复数据\n\n### 方法说明\n\n使用 `drop_duplicates()` 删除重复的行。\n\n**语法:**\n```python\ndf.drop_duplicates(subset=None, keep='first', inplace=False)\n```\n\n**参数:**\n- `subset`: 指定列，只考虑这些列的重复\n- `keep`: 'first'(保留第一个), 'last'(保留最后一个), False(全部删除)\n- `inplace`: 是否直接修改原 DataFrame\n\n**特点:**\n- 默认考虑所有列\n- 可以只基于部分列判断重复"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例1: 创建含重复数据的 DataFrame"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.DataFrame({\n    '姓名': ['张三', '李四', '张三', '王五', '李四'],\n    '年龄': [25, 30, 25, 35, 30],\n    '城市': ['北京', '上海', '北京', '广州', '上海']\n})\n\nprint(\"原始 DataFrame（含重复）:\")\nprint(df)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例2: 删除完全重复的行\n\n所有列的值都相同才算重复。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_unique = df.drop_duplicates()\nprint(\"删除完全重复的行:\")\nprint(df_unique)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例3: 基于特定列删除重复\n\n只根据姓名列判断是否重复。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_unique = df.drop_duplicates(subset=['姓名'])\nprint(\"基于姓名列删除重复:\")\nprint(df_unique)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例4: 保留最后一个重复项\n\n使用 `keep='last'` 保留最后出现的重复项。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_unique = df.drop_duplicates(subset=['姓名'], keep='last')\nprint(\"保留最后一个:\")\nprint(df_unique)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. 删除缺失值\n\n### 方法说明\n\n使用 `dropna()` 删除包含缺失值的行或列。\n\n**语法:**\n```python\ndf.dropna(axis=0, how='any', subset=None)\n```\n\n**参数:**\n- `axis`: 0 删除行，1 删除列\n- `how`: 'any'(任何缺失值), 'all'(全部缺失值)\n- `subset`: 只考虑指定的列\n- `thresh`: 至少有 thresh 个非缺失值才保留\n\n**特点:**\n- 默认删除任何包含缺失值的行\n- 可以只删除全部为缺失值的行"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例1: 创建含缺失值的 DataFrame"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.DataFrame({\n    'A': [1, 2, np.nan, 4],\n    'B': [5, np.nan, np.nan, 8],\n    'C': [9, 10, 11, 12]\n})\n\nprint(\"原始 DataFrame（含缺失值）:\")\nprint(df)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例2: 删除含有缺失值的行\n\n默认行为，删除任何包含 NaN 的行。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_clean = df.dropna()\nprint(\"删除含缺失值的行:\")\nprint(df_clean)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例3: 删除含有缺失值的列\n\n使用 `axis=1` 删除列。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_clean = df.dropna(axis=1)\nprint(\"删除含缺失值的列:\")\nprint(df_clean)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 示例4: 删除全部为缺失值的行\n\n使用 `how='all'` 只删除全部为 NaN 的行。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df_clean = df.dropna(how='all')\nprint(\"删除全部为缺失值的行:\")\nprint(df_clean)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 总结\n\n### 删除方法对比\n\n| 方法 | 用途 | 修改原数据 | 返回值 |\n|------|------|-----------|--------|\n| `drop()` | 删除行或列 | 否（除非 inplace=True） | 新 DataFrame |\n| `del` | 删除列 | 是 | None |\n| `pop()` | 删除列并返回 | 是 | 被删除的列 |\n| `drop_duplicates()` | 删除重复行 | 否 | 新 DataFrame |\n| `dropna()` | 删除缺失值 | 否 | 新 DataFrame |\n\n### 关键要点\n\n1. `drop()` 默认不修改原 DataFrame\n2. 使用 `axis=1` 或 `columns` 参数删除列\n3. 使用 `axis=0` 或 `index` 参数删除行\n4. `errors='ignore'` 可以忽略不存在的标签\n5. 避免使用 `inplace=True`，保持数据不可变性\n6. `drop_duplicates()` 用于删除重复数据\n7. `dropna()` 用于删除缺失值"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.8.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}